//
//  JPHomeViewController.m
//  JPKY
//
//  Created by Vitas on 2016/11/13.
//  Copyright © 2016年 Vitas. All rights reserved.
//

#import "JPHomeViewController.h"
#import "JPWeatherView.h"
#import <SDCycleScrollView.h>
#import "JPSubtitesSV.h"
#import "JPTumourAppointmentVC.h"
#import "NSAttributedString+HMAdditon.h"
#import "JPFlunkModel.h"
#import "UIColor+HMAddition.h"
#import "JPPublicBenefitActivityVC.h"
#import "InterfaceTool.h"
#import "XRCarouselView.h"
#import "JPRegisterVC.h"
#import "JPWeatherModel.h"
#import "JPNewFeatureView.h"

@interface JPHomeViewController ()


/**
 图文混排数据数组
 */
@property (nonatomic, copy) NSArray <JPFlunkModel *> *apps;

/**
 轮播器
 */
@property (weak,nonatomic) XRCarouselView *slideView;

/**
 天气数据
 */
@property (strong,nonatomic) JPWeatherModel *weatherModel;

/**
 天气
 */
@property (weak,nonatomic) JPWeatherView *weatherView;

@end

@implementation JPHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 记录天气模型
    self.weatherModel = [[JPWeatherModel alloc] init];
    // 加载科室数据
    [self loadPlist];
    // 加载天气数据
    [self loadData];
    // 加载主界面数据
    [self setupUI];
    // 根据版本号判断是否加载新特性界面
    if ([self judgeVersionNumber]){
    [self appearNewFeature];
    }
}

- (void)setupUI {
    
    // 装载六个按钮的容器
    UIView *vb = [[UIView alloc] init];
    vb.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:vb];
    [vb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-44);
        make.width.equalTo(self.view);
        make.height.mas_equalTo(vb.mas_width).multipliedBy(2/3.0);
    }];
    // 创建六个科室按钮
    for (int i = 0; i < 6; i++) {
        
        CGFloat btnW = self.view.bounds.size.width / 3;
        CGFloat btnH = btnW;
        CGFloat btnX = btnW * (i % 3);
        CGFloat btnY = btnH * (i / 3);
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        CGColorRef color = [UIColor blackColor].CGColor;
        [btn.layer setBorderColor:color];
        [btn.layer setBorderWidth:0.5];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        [vb addSubview:btn];
        btn.tag = i + 1;
        
        // 图文混排
        NSAttributedString *attrStr = [NSAttributedString hm_imageTextWithImage:[UIImage imageNamed:self.apps[i].icon] imageWH:50 title:self.apps[i].name fontSize:14 titleColor:[UIColor blackColor] spacing:15];
        
        // 设置button的属性文本
        [btn setAttributedTitle:attrStr forState:UIControlStateNormal];
        // 设置Button允许多行
        btn.titleLabel.numberOfLines = 0;
        // 设置Button的文字居中
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        // 设置点击跳转的方法
        [btn addTarget:self action:@selector(pushDetails:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // 创建字幕滚动条
    JPSubtitesSV *vz = [[JPSubtitesSV alloc] initWithFrame:CGRectMake(self.view.bounds.size.width * 0.3, 200, self.view.bounds.size.width, 50) textArray:@[@"黯然销魂组:",@"组长:刘伟棠",@"吴俊杰",@"周述坚",@"刘佳"] colorArray:@[[UIColor redColor],[UIColor blueColor]]];
    vz.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:vz];
    [vz mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(vb.mas_top);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.1f);
    }];

    // 创建轮播器
    XRCarouselView *sv = [[XRCarouselView alloc] init];
    [self.view addSubview:sv];
    self.slideView = sv;
    sv.time = 2.5;
    sv.changeMode = ChangeModeFade;
    sv.pagePosition = PositionHide;
    sv.backgroundColor = [UIColor whiteColor];
    [self loadImagesUrl];
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(vz.mas_top);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.55f);
    }];
    
    // 创建顶部天气视图
    JPWeatherView *weatherView = [[JPWeatherView alloc] init];
    self.weatherView = weatherView;
    weatherView.backgroundColor = [UIColor hm_colorWithRed:230.0 green:246.0 blue:249.0];
    [self.view addSubview:weatherView];
    [weatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.2f);
    }];
    
    // 字幕标题
    UIView *subtitView = [[UIView alloc] init];
    [self.view addSubview:subtitView];
    subtitView.backgroundColor = [UIColor whiteColor];
    [subtitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.bottom.equalTo(vb.mas_top);
        make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.4f);
        make.height.mas_equalTo(vz.mas_height);
    }];
    UILabel *subtitLabel = [[UILabel alloc] init];
    [subtitView addSubview:subtitLabel];
    subtitLabel.text = @"名医一点通";
    subtitLabel.font = [UIFont systemFontOfSize:15];
    [subtitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(subtitView.mas_centerX);
        make.centerY.equalTo(subtitView.mas_centerY);
    }];
    UIImageView *subtitImageView = [[UIImageView alloc] init];
    [subtitImageView setImage:[UIImage imageNamed:@"yj"]];
    [subtitView addSubview:subtitImageView];
    [subtitImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(subtitView);
        make.right.equalTo(subtitLabel.mas_left).offset(-10);
    }];
    [subtitImageView sizeToFit];
    
}


/**
 加载科室数据
 */
- (NSArray *)loadPlist {
    
    // 懒加载
    if (_apps == nil) {
        
        // 读取plist文件全路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"JPFlunkButton.plist" ofType:nil];
        
        //2.加载数组,读出plist中的数据
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
        
        //3.将dicArray 中的字典转成模型对象,放到新的数组中
        //遍历dictArray数组
        //4.创建一个可变数组,把模型存到可变数组中
        NSMutableArray *dicArray = [NSMutableArray array];
        for (NSDictionary *dic in dictArray) {
            //初始化模型对象
            JPFlunkModel *hero = [JPFlunkModel flunkModelWithDic:dic];
            [dicArray addObject:hero];
        }
        //5.赋值
        self.apps = dicArray;
    }
    return _apps;
}

/**
 *  加载图片数组的方法
 */
-(void)loadImagesUrl{
    
    __block NSMutableArray *imgURLArr = [NSMutableArray array];

    [[InterfaceTool sharedInterfaceTool] getScrollImageSuccess:^(id response) {
        if (response != nil) {
            NSDictionary *dict = response;
            dict = dict[@"data"];
            NSArray *dictArr = dict[@"banners"];
            for (int i = 0; i < dictArr.count; i++) {
                NSDictionary *imgDict = dictArr[i];
                NSString *imgURLString = imgDict[@"banner_img_url"];
                [imgURLArr addObject:imgURLString];
            }
            self.slideView.imageArray = imgURLArr;
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 科室Button跳转方法
 */
- (void)pushDetails:(UIButton *)btn {
    
    NSInteger num = btn.tag;
    switch (num) {
        case 1:{
            NSString *str = @"肿瘤";
            [self setTitleWithDoctor:str tag: num];
        }
            break;
        case 2:{
            NSString *str = @"血液科";
           [self setTitleWithDoctor:str tag: num];
        }
            break;

        case 3:{
            NSString *str = @"心血管";
            [self setTitleWithDoctor:str tag: num];
        }
            break;

        case 4:{
            NSString *str = @"神经科";
            [self setTitleWithDoctor:str tag: num];
        }
            break;

        case 5:{
            NSString *str = @"骨科";
            [self setTitleWithDoctor:str tag: num];
        }

            break;

        case 6:{
            JPPublicBenefitActivityVC *publiView = [[JPPublicBenefitActivityVC alloc] init];
            
            publiView.view.backgroundColor = [UIColor yellowColor];
            [self.navigationController pushViewController:publiView animated:YES];
        }
            break;
        default:
            break;
    }
    
}

/**
 科室按钮跳转方法
 */
- (void)setTitleWithDoctor: (NSString *)str tag:(NSInteger)tag{
    
    JPRegisterVC *tumourVC = [[JPRegisterVC alloc] init];
    tumourVC.titleStr = str;
    tumourVC.tag = tag;
    tumourVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:tumourVC animated:YES];
}

// 获取天气数据
- (void)loadData {
    
    [[InterfaceTool sharedInterfaceTool] getWeatherSuccess:^(id response) {
        JPWeatherModel *model = [[JPWeatherModel alloc] init];
        //接收字典数据
        NSDictionary *responseDict = response;
        //抓取日期信息
        model.date = responseDict[@"date"];

        NSArray <NSDictionary *> *resultsArr = responseDict[@"results"];
        model.currentCity = resultsArr.lastObject[@"currentCity"];
        NSArray <NSDictionary *> *weatherDictArr = resultsArr.lastObject[@"weather_data"];
        model.weather = weatherDictArr.firstObject[@"weather"];
        model.temperature = weatherDictArr.firstObject[@"temperature"];
        model.dayPictureUrl = weatherDictArr.firstObject[@"dayPictureUrl"];
        self.weatherModel = model;
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 获取天气模型方法
 */
- (void)setWeatherModel:(JPWeatherModel *)weatherModel{
    
    _weatherModel = weatherModel;
    self.weatherView.weatherModel = weatherModel;
}

- (BOOL)judgeVersionNumber {
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    // 版本号
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    if (![userDefault objectForKey:@"JPKYVersionNumber"]) {
        
        [userDefault setObject:app_Version forKey:@"JPKYVersionNumber"];
        return YES;
    } else if(![app_Version isEqualToString:[userDefault objectForKey:@"JPKYVersionNumber"]]){
    
    [userDefault setObject:app_Version forKey:@"JPKYVersionNumber"];
        return YES;
    }
    return NO;
}
/**
 加载新特性界面
 */
- (void)appearNewFeature {
    
    JPNewFeatureView *newFeatureView = [[JPNewFeatureView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    UIWindow* keyWindow = [UIApplication sharedApplication].keyWindow;
    
    // 将新特性界面
    [keyWindow addSubview:newFeatureView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
